
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

const jwt = require("./utils/jwt.js")



const cors = require('cors');

require("./config/mongodb")




var indexRouter = require('./routes/indexRouter.js');
var userRouter = require('./routes/userRouter.js');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



const corsOptions = {
  origin: '*',
  exposedHeaders: ['Authorization'],       // 关键：暴露 Authorization 头
  credentials: true                        // 允许凭证传输
};
app.use(cors(corsOptions));



app.use((req, res, next) => {
  //判断缩放有token
  //有校验
  //如果没有
  if (req.url.includes("login")) {
    next()
    return
  }
  if (req.url.includes("register")) {
    next()
    return
  }



  if (req.url.includes("api")) {
    const token = req.headers["authorization"]
    console.log(jwt.verify(token));
    if (jwt.verify(token)) {
      const parse = jwt.verify(token)
      console.log(parse.exp - parse.iat);
      next()
      return
    } else {
      res.status(401).json({ status: 0, message: "api没有授权" })
      return
    }
  }

  next()


})





app.use("/", indexRouter)

app.use('/api', userRouter);






module.exports = app;
